const express = require('express');
const router = express.Router();
const db = require('../../../MySql');
const { generate19DigitId } = require('../../utils/idUtils')

//body参数：
// {
//     "repoIds": [
//         "1757909353925175090"
//     ],
//     "quIds": [
//         "1587622642263625729",
//         "1587622642393649153"
//     ],
//     "remove": false
// }
router.post('/repo/batch-action', async (req, res) => {
    try {

        const id = generate19DigitId()
        const { quIds, repoIds, remove } = req.body

        let sql = ''
        if (remove) {
            // 移出题库功能：删除关联关系
            sql = `delete from el_qu_repo where qu_id in (?) and repo_id in (?)`
            await db.query(sql, [quIds, repoIds])

        } else {
            const [results] = await db.query(`select eq.id,eq.qu_type 
                from el_qu eq join el_qu_repo eqr on eqr.qu_id=eq.id where eqr.qu_id in (${quIds.join(',')})`)

            sql = `insert into el_qu_repo(id,qu_id,repo_id,qu_type,sort) values (?,?,?,?,?)`

            const quTypeMap = {}
            results.forEach(item => {
                quTypeMap[item.id] = item.qu_type
            })

            // 构建批量插入的值
            const values = []
            for (const repoId of repoIds) {
                for (let i = 0; i < quIds.length; i++) {
                    const quId = quIds[i]
                    const quType = quTypeMap[quId]
                    if (quType) {
                        values.push([generate19DigitId(), quId, repoId, quType, i + 1])
                    }
                }
            }
            // 批量插入
            if (values.length > 0) {
                sql = `insert into el_qu_repo(id, qu_id, repo_id, qu_type, sort) values ?`
                await db.query(sql, [values])
            }
        }
        return res.json({ "msg": "请求成功！", "code": 0, "success": true })
    } catch (error) {
        console.error(error)
        return res.status(500).json({
            msg: 'Internal server error',
            code: 500,
            success: false
        })
    }
})


module.exports = router